<template>
    <div>
        <el-dialog title="分配角色" :visible.sync="roleVisible" :close-on-click-modal="false" :close-on-press-escape="false"
            @closed="handlerCancel()">
            <el-checkbox-group v-model="checkList">
                <el-checkbox v-for="item in roles" :label="item.id" :key="item.id">
                    {{ item.roleName }}
                </el-checkbox>
            </el-checkbox-group>
            <div slot="footer" class="dialog-footer">
                <el-button @click="handlerCancel()">取 消</el-button>
                <el-button type="primary" @click="handlerAssignRole()">分配角色</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { useInfByIdoApi, addUseApi, editUseApi } from '../../api/UseApi.js'
import { rolesApi, roleByUserApi, assignRoleApi } from '../../api/RoleApi.js'
export default {
    props: ['roleVisible'],
    data() {
        return {
            roles: [],
            checkList: [],
            userId: '',
            formLabelWidth: '120px',
        };
    },
    mounted() {
        this.loadROLES();
    },
    methods: {
        handlerCancel() {
            this.$emit('closeDialog');

        },
        async handlerAssignRole() {
            try {
                const data = {
                    userId: this.userId,
                    roleIds:this.checkList,
                }
                const res = await assignRoleApi(data);
                if (res.status === 200) {
                    this.$emit('closeDialog', true);
                } else {
                    this.$message.error(res.msg);
                }
            } catch (error) {
                console.error('获取用户列表失败:', error);
                this.$message.error('网络错误，请稍后重试');
            }



        },
        async openDialog(userId) {
            this.userId = userId;
            try {
                const res = await roleByUserApi(userId);
                if (res.status === 200) {
                    this.checkList = res.data.map((item) => item.id);
                } else {
                    this.$message.error(res.msg);
                }
            } catch (error) {
                console.error('获取用户列表失败:', error);
                this.$message.error('网络错误，请稍后重试');
            }
        },
        async loadROLES() {
            try {
                const res = await rolesApi();
                if (res.status === 200) {
                    this.roles = res.data;
                } else {
                    this.$message.error(res.msg);
                }
            } catch (error) {
                console.error('获取用户列表失败:', error);
                this.$message.error('网络错误，请稍后重试');
            }

        },


    }
};

</script>
<style scoped lang="less"></style>